package nc.bs.voucher.impl;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import nc.bs.dao.BaseDAO;
import nc.bs.framework.common.NCLocator;
import nc.bs.voucher.itf.IVourcherSumService;
import nc.itf.gl.voucher.IVoucher;
import nc.jdbc.framework.processor.MapListProcessor;
import nc.jdbc.framework.processor.MapProcessor;
import nc.vo.gl.pubvoucher.VoucherVO;
import nc.vo.glcom.ass.AssVO;
import nc.vo.ml.NCLangRes4VoTransl;
import nc.vo.pub.BusinessException;
import nccloud.bs.gl.voucher.AccountingbookQryBO;
import nccloud.bs.gl.voucher.VoucherWebQryBO;
import nccloud.dto.gl.lightgl.VoucherDetailMDVO;
import nccloud.dto.gl.lightgl.VoucherMDVO;

@SuppressWarnings("restriction")
public class VourcherSumServiceImpl implements IVourcherSumService {
	private BaseDAO dao;
	@Override
	public Map<String, Object> queryBookCombineInfos(String pk_accasoa, String dbilldate, boolean isVoucher)
			throws BusinessException {
		return new AccountingbookQryBO().queryBookCombineInfo(pk_accasoa, dbilldate, isVoucher);
	}

	@Override
	public VoucherMDVO showSumDetails(String pk_voucher, List<String> ids, List<String> fzhss) throws BusinessException {
		return showSumDetail(pk_voucher, ids, fzhss);
	}

	@SuppressWarnings({ "rawtypes", "unchecked" })
	@Override
	public JSONArray handlerchildrendatas(String pk_voucher, String pk_accountingbook) throws BusinessException {
		JSONArray jsonArray = new JSONArray();
		String sql = buildChildrendataSQL(pk_voucher, pk_accountingbook);
		List<Map<String,Object>> listMaps = (List<Map<String, Object>>)getDao().executeQuery(sql, new MapListProcessor());
		JSONObject json = new JSONObject();
		json.put("title", "辅助核算");
		json.put("key", "fzhs");
		if(listMaps != null && !listMaps.isEmpty()) {
			JSONArray childrens = new JSONArray();
			for(Map<String, Object> map : listMaps) {
				JSONObject children = new JSONObject();
				children.put("key", map.get("classid"));
				children.put("title", map.get("name"));
				childrens.add(children);
			}
			json.put("children", childrens);
		}else {
			json.put("children", new ArrayList());
		}
		jsonArray.add(json);
		return jsonArray;
	}

	@Override
	public Map queryVoucherInfo(Map<String, Object> map) throws BusinessException {
		Map<Object, Object> qryMap = new HashMap<>();
		String[] billDates = map.get("billdate").toString().split("-");
		String year = billDates[0];
		String month = billDates[1];
		Object voucherNo = map.get("billcode");
		Object pk_group = map.get("pk_group");
		Object pk_org = map.get("pk_org");
		Map<Object, Object> vmap = (Map<Object, Object>)this.getDao().executeQuery(this.buildVoucherSQL(pk_group, pk_org, year, month, voucherNo), new MapProcessor());
		if (vmap == null || vmap.isEmpty()) return qryMap;
		qryMap.put("id", vmap.get("id"));
		qryMap.put("pk_srcbilltype", vmap.get("pk_vouchertype"));
		return qryMap;
	}

	/**
	 *
	 * 构建凭证查询SQL
	 * @param pk_group
	 * @param pk_org
	 * @param year
	 * @param month
	 * @param VoucherNo
	 * @return
	 * @throws BusinessException
	 */
	protected String buildVoucherSQL(Object pk_group,Object pk_org,Object year,Object month, Object VoucherNo) throws BusinessException{
		StringBuilder sql = new StringBuilder();
		sql.append(" SELECT\n ");
		sql.append("\tpk_voucher id,\n");
		sql.append("\tpk_vouchertype,\n ");
		sql.append("\tperiod,\n ");
		sql.append("\tyear,\n ");
		sql.append("\tnum \n");
		sql.append("FROM\n" );
		sql.append("\tGL_VOUCHER \n" );
		sql.append("WHERE\n" );
		sql.append("\tdr = 0 \n" );
        sql.append("\tand PK_GROUP = '"+pk_group+"' \n" );
		sql.append("\tAND pK_org = '"+pk_org+"'\n" );
		sql.append("\tAND year = '"+year+"' \n" );
		sql.append("\tAND period = '"+month+"' \n" );
		sql.append("\tAND num =  " + VoucherNo);
		return sql.toString();
	}


	/**
	  *  构建辅助核算节点查询SQL
	 * @param pk_voucher
	 * @param pk_accountingbook
	 * @return
	 * @throws BusinessException
	 */
	public String buildChildrendataSQL(String pk_voucher, String pk_accountingbook) throws BusinessException{
        String sql = "select distinct  fhb.classid,md.defaulttablename,fhb.code,fhb.name " +
                "  from gl_detail glb " +
                "  inner join  bd_account kjkm on kjkm.pk_account =  glb.pk_account " +
                "  inner join bd_accchart km on kjkm.pk_accchart = km.pk_accchart " +
                "  inner join bd_accass fh on fh.pk_accchart = km.pk_accchart " +
                "  inner join bd_accassitem fhb on fh.pk_entity = fhb.pk_accassitem " +
                "  inner join md_class md on fhb.classid = md.id  " +
                " and  glb.dr = 0 and fh.dr = 0 and fhb.dr = 0 and km.dr = 0 and kjkm.dr = 0 " +
                "where glb.pk_voucher = '" + pk_voucher + "' " +
                " and glb.pk_accountingbook = '" + pk_accountingbook + "' ";
		return sql;
	}
	
	/**
	 * 
	  * 获取凭证分录汇总的规则
	 * @param vo
	 * @param ids 汇总方式
	 * @return
	 * @throws BusinessException
	 */
	public String getkey(VoucherDetailMDVO vo, List<String> ids, List<String> fzhss) throws BusinessException{
		// 摘要 + 会计科目 + 辅助核算
		String key = "";
		if(ids != null && !ids.isEmpty()) {
			for(String id : ids) {
				if("1".equals(id)) {
					key += vo.getExplanation();
				}else if("2".equals(id)){
					key += vo.getPk_accasoa();
				}
			}
		}
		if(fzhss != null && !fzhss.isEmpty()) {
			String assid = vo.getAssid();
			if(assid != null) {
				for(String fzhs: fzhss) {
					AssVO[] asss = vo.ass;
					for(AssVO assvo : asss ) {
						if(fzhs.equals(assvo.getM_classid())) {
							key  += fzhs;
						}
					}
				}
			}else {
				key += "空辅助核算";
			}
		}
		
		return key;
		
	}
	
	public VoucherMDVO showSumDetail(String pk_voucher, List<String> ids, List<String> fzhss) throws BusinessException {
		VoucherVO voucher = NCLocator.getInstance().lookup(IVoucher.class).queryByPk(pk_voucher);
		if (voucher == null) {
			throw new BusinessException(NCLangRes4VoTransl.getNCLangRes().getStrByID("20021005", "UPP20021005-000538"));
		} else {
			VoucherMDVO mdVO = this.transVoucherVO(voucher);
			VoucherDetailMDVO[] detailMDVOs = mdVO.getDetailMDVOs();
			ArrayList<VoucherDetailMDVO> lists = new ArrayList<VoucherDetailMDVO>();
			HashMap<String, Integer> uniqueness = new  HashMap<String, Integer>(); // 通过 
			if (detailMDVOs != null && detailMDVOs.length > 0) {
				for(int i=0 ; i < detailMDVOs.length ; i++) {
					VoucherDetailMDVO detailMDVO = detailMDVOs[i];
					// 会计科目 +摘要 + 辅助核算
					String key = getkey(detailMDVO, ids, fzhss);
					if(uniqueness.isEmpty()) {
						uniqueness.put(key, i);
						lists.add(detailMDVO);
					}else {
						if(uniqueness.containsKey(key)) {
							for(VoucherDetailMDVO vo : lists) {
								String keyy = getkey(vo,ids,fzhss);
								if(keyy.equals(key)) {
									vo.setLocaldebitamount(vo.getLocaldebitamount().add(detailMDVO.getLocaldebitamount()));  // 账簿本币(借方)
									vo.setLocalcreditamount(vo.getLocalcreditamount().add(detailMDVO.getLocalcreditamount())); // 账簿本币(贷方)
								}
							}
						}else {
							uniqueness.put(key, i);
							lists.add(detailMDVO);
						}
					}
				}
				mdVO.setDetailMDVOs(lists.toArray(new VoucherDetailMDVO[lists.size()]));
			}
			return mdVO;
		}
	}
	
	
	private VoucherMDVO transVoucherVO(VoucherVO voucher) throws BusinessException {
		VoucherMDVO mdVO = new VoucherMDVO(voucher, true);
		Map<String, String> systemMap = (new VoucherWebQryBO()).getSystemName(new String[]{voucher.getPk_system()});
		voucher.setSystemname(systemMap.get(voucher.getPk_system()));
		VoucherDetailMDVO[] mdetails = (new VoucherWebQryBO()).catSubjName(mdVO.getDetailMDVOs());
		mdVO.setDetailMDVOs(mdetails);
		return mdVO;
	}

	public BaseDAO getDao() {
		return dao == null ?  new BaseDAO() : dao;
	}
	
	
}
